/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cjt2325.cameraview;

import static ohos.bundle.IBundleManager.PERMISSION_GRANTED;

import com.cjt2325.cameraview.listener.PermissionInterface;
import com.cjt2325.cameraview.slice.CameraMainSlice;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.security.SystemPermission;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Main Ability
 */
public class MainAbility extends Ability {
    /**
     * REQ PERMISSION CODE
     */
    public static final int REQ_PERMISSION_CODE = 1001;

    private PermissionInterface mPermissionListener;
    private List<String> mPermissions =
            new LinkedList<>(
                    Arrays.asList(
                            SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE));

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(CameraMainSlice.class.getName());
        reqPermissions();
    }

    private void reqPermissions() {
        mPermissions.removeIf(perM -> verifySelfPermission(perM) == PERMISSION_GRANTED || !canRequestPermission(perM));
        if (!mPermissions.isEmpty()) {
            requestPermissionsFromUser(
                    mPermissions.toArray(new String[mPermissions.size()]), MainAbility.REQ_PERMISSION_CODE);
        }
    }

    /**
     * set Permission Listener
     *
     * @param permissionListener PermissionInterface
     */
    public void setPermissionListener(PermissionInterface permissionListener) {
        this.mPermissionListener = permissionListener;
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] ss, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, ss, grantResults);
        if (requestCode != REQ_PERMISSION_CODE) {
            return;
        }
        boolean isHavePermission = false;
        for (int i = 0; i < ss.length; i++) {
            isHavePermission = grantResults[i] == PERMISSION_GRANTED;
        }
        if (isHavePermission) {
            restart();
        }
    }
}
